package com.situ.crm.service.impl;


import com.situ.crm.mapper.CustomerLossMapper;
import com.situ.crm.mapper.CustomerMapper;
import com.situ.crm.mapper.OrderMapper;
import com.situ.crm.pojo.entity.Customer;
import com.situ.crm.pojo.entity.CustomerLoss;
import com.situ.crm.pojo.entity.Order;
import com.situ.crm.service.ICustomerLossService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

// 类里面所有的方法都加上了事物
@Transactional
@Service
public class CustomerLossServiceImpl implements ICustomerLossService {
    @Autowired
    private CustomerMapper customerMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private CustomerLossMapper customerLossMapper;

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public void checkCustomerLoss() {
        // 开启事物

        System.out.println("CustomerLossServiceImpl.checkCustomerLoss");
        // 在客户订单表order表里面查询最近最近六个月都没有订单的客户
        // 1.查找所有流失的客户
        List<Customer> customerList = customerMapper.selectCustomerLoss();
        for(Customer customer : customerList) {
            System.out.println(customer);
            // 2.实例化CustomeLoss对象，每一个对象对应一个流失课客户
            CustomerLoss customerLoss = new CustomerLoss();
            customerLoss.setCustomerId(customer.getId());
            customerLoss.setCustomerName(customer.getName());

            // 3.查询这个客户最后一次的订单信息
            Order order = orderMapper.selectLastOrderByCustomerId(customer.getId());
            if (order != null) {// 这个客户之前下过订单，但是6个月内没有
                customerLoss.setLastOrderTime(order.getOrderDate());
            } /*else {// 这个客户之前一直就没有订单
                customerLoss.setLastOrderTime(null);
            }*/

            // 4、添加到客户流失表里面
            customerLossMapper.insert(customerLoss);
        }

        // 关闭事物
    }
}
